export const sessionStorage = {
    getItem (key) {
        if (process.client) {
            let _r = window.sessionStorage.getItem(key)
            if (_r && /^\{.*\}$/.test(_r)) _r = JSON.parse(_r)
            return _r
        }
        return null
    },
    setItem (key, value) {
        if (typeof value === typeof {}) value = JSON.stringify(value)
        window.sessionStorage.setItem(key, String(value))
    },
    removeItem (key) {
        if (key === 'ALL') {
            window.sessionStorage.clear()
            return
        }
        if (Object.prototype.toString.call(key) === '[object String]') {
            window.sessionStorage.removeItem(key)
            return
        }
        if (Object.prototype.toString.call(key) === '[object Array]' && key.length === 0) {
            window.sessionStorage.removeItem(key[0])
        } else {
            key.map(index => window.sessionStorage.removeItem(index))
        }
    }
}
export const localStorage = {
    getItem (key) {
        if (process.client) {
            let _r = window.localStorage.getItem(key)
            if (_r && /^\{.*\}$/.test(_r)) _r = JSON.parse(_r)
            return _r
        }
        return null
    },
    setItem (key, value) {
        if (typeof value === typeof {}) value = JSON.stringify(value)
        window.localStorage.setItem(key, String(value))
    },
    removeItem (key) {
        if (process.client) {
            if (key === 'ALL') {
                window.localStorage.clear()
                return
            }
            if (Object.prototype.toString.call(key) === '[object String]') {
                window.localStorage.removeItem(key)
                return
            }
            if (Object.prototype.toString.call(key) === '[object Array]' && key.length === 0) {
                window.localStorage.removeItem(key)
            } else {
                key.map(index => window.localStorage.removeItem(index))
            }
        }
    }
}

export const getCookiesInServer = (req) => {
    const serviceCookie = {}
    req &&
        req.headers.cookie &&
        req.headers.cookie.split(';').forEach(function (val) {
            const parts = val.split('=')
            serviceCookie[parts[0].trim()] = (parts[1] || '').trim()
        })
    return serviceCookie
}

export const removeSpaces = (data) => {
    if (data === null || data === undefined) {
        return data
    }
    if (typeof data === 'object') {
        Object.keys(data).forEach((key) => {
            if (typeof data[key] === 'object') {
                data[key] = removeSpaces(data[key])
            } else if (typeof data[key] === 'string') {
                data[key] = data[key].replace(/(^\s*)|(\s*$)/g, '')
            }
        })
        return data
    } else if (typeof data === 'string') {
        return data.replace(/(^\s*)|(\s*$)/g, '')
    } else {
        return data
    }
}

export function getUUID () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        // const r = "r&0x3" | "0x8";
        const r = 8
        return (c === 'x' ? (Math.random() * 16) | 0 : r).toString(16)
    })
}

export function getWidthHeight (file) {
    return new Promise((resolve) => {
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = () => {
            resolve({
                width: img.width,
                height: img.height
            })
        }
        img.src = _URL.createObjectURL(file)
    })
}

export const addWatermark = {
    base64ToBlob (base64) {
        const arr = base64.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
    },
    /**
     * 给图片增加图片水印
     * @param {File} file 图片
     * @returns {File} 增加水印后的图片
     */
    async add (file) {
        let blob = {}
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        await new Promise((resolve) => {
            img.onload = async () => {
                const canvas = document.createElement('canvas')
                canvas.width = img.width
                canvas.height = img.height
                const context = canvas.getContext('2d')
                context.drawImage(img, 0, 0)
                // 水印图片
                const watermarkImg = new Image()
                watermarkImg.src = require('@/assets/images/watermark-img.png')
                await new Promise((resolve) => {
                    watermarkImg.onload = () => {
                        context.drawImage(watermarkImg, (img.width - img.width / 2) / 2, (img.height - img.width / 2 / 2.65) / 2, img.width / 2, img.width / 2 / 2.65)
                        const base64 = canvas.toDataURL('image/png')
                        blob = this.base64ToBlob(base64)
                        resolve()
                    }
                })
                resolve()
            }
        })
        return new File([blob], file.name, {
            type: file.type
        })
    }
}
